package com.bsj.pay.controller.admin;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bsj.pay.common.Result;
import com.bsj.pay.config.GlobalConfig;
import com.bsj.pay.model.ChargeAccountBean;
import com.bsj.pay.model.OrderBean;
import com.bsj.pay.model.PartnerBean;
import com.bsj.pay.service.ChargeAccountService;
import com.bsj.pay.service.LogService;
import com.bsj.pay.service.OrderService;
import com.bsj.pay.service.PartnerService;
import com.bsj.pay.util.HttpUtil;
import com.bsj.pay.util.ResultUtil;
import com.bsj.pay.util.http.Http;
import com.bsj.pay.util.http.Http.Response;
import com.bsj.pay.util.security.MD5;
import com.bsj.pay.util.security.PassWrodsCreater;
import com.github.pagehelper.PageInfo;

import net.sf.json.JSONObject;

@Controller("adminChargeAccountController")
@RequestMapping("/admin/chargeAccount")	
public class ChargeAccountController {
	
	@Autowired
	private ChargeAccountService chargeAccountService;
	
	@Autowired
	private PartnerService partnerService;
	
	@Autowired
	private LogService logService;
	
	@Autowired
	private OrderService orderService;
	
	@ResponseBody
	@RequestMapping(value = "/list.html")
	public Map list(HttpServletRequest req, HttpServletResponse res,int page,int limit,ChargeAccountBean chargeAccount) {
		ChargeAccountBean queryModel=new ChargeAccountBean();
		if(!StringUtils.isEmpty(chargeAccount.getType()))queryModel.setType(chargeAccount.getType());
		if(!StringUtils.isEmpty(chargeAccount.getPartner_order_no()))queryModel.setPartner_order_no(chargeAccount.getPartner_order_no());
		if(!StringUtils.isEmpty(chargeAccount.getAccount()))queryModel.setAccount(chargeAccount.getAccount());
		if(chargeAccount.getStatus()!=null)queryModel.setStatus(chargeAccount.getStatus());
		if(chargeAccount.getAmount()!=null)queryModel.setAmount(chargeAccount.getAmount());
		if(chargeAccount.getCharge_status()!=null)queryModel.setCharge_status(chargeAccount.getCharge_status());
		if(chargeAccount.getNotify_status()!=null)queryModel.setNotify_status(chargeAccount.getNotify_status());
		if(chargeAccount.getPartner_id()!=null)queryModel.setPartner_id(chargeAccount.getPartner_id());
		PageInfo<ChargeAccountBean> pageInfo=chargeAccountService.pageList(queryModel, page, limit);
		return ResultUtil.getQuerySuccessResult(pageInfo);
	}
	
	@RequestMapping("/listPage.html")
    public ModelAndView listPage(HttpServletRequest request,HttpServletResponse response,ModelAndView mav) {
		mav.addObject("partners", partnerService.queryAll());
		mav.setViewName("admin/charge/list");
		return mav;
    }
	
	@ResponseBody
	@RequestMapping(value = "/notify.html")
	public Result callback(HttpServletRequest req, HttpServletResponse res,Long id) {
		logService.addLog(req, "补单给合作商,单号:"+id);
		Result result=new Result();
		if(id==null)
		{
			result.setCode(0);
			result.setMsg("参数异常");
			return result;
		}
		try {
			if(!chargeAccountService.partnerNotify(id))
			{
				result.setCode(1);
				result.setMsg("回调失败");
				return result;
			}
			result.setCode(0);
			result.setMsg("操作成功");
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(500);
			result.setMsg(e.getMessage());
			return result;
		}
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/testCharge.html")
	public Result testCharge(HttpServletRequest request,HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		Result result=new Result();
		PartnerBean partner=partnerService.getById(10000l);
		if(partner==null)
		{
			result.setCode(0);
			result.setMsg("测试合作商不存在");
			result.setData("");
			return result;
		}
		String partner_id=String.valueOf(partner.getId());
		String partner_order_no=PassWrodsCreater.getUUIDStr();
		String account=request.getParameter("account");
		String amount=request.getParameter("amount");
		String type=request.getParameter("type");
		String area=request.getParameter("area");
		String notify_url=HttpUtil.getServerPath(request)+"api/testPartnerNotifyUrl.html";
		String sign=MD5.getMD5(partner_id+partner_order_no+account+amount+type+area+notify_url+partner.getApi_key());
		Map<String,String> param=new HashMap<String,String>();
		param.put("partner_id", partner_id);
		param.put("partner_order_no", partner_order_no);
		param.put("account", account);
		param.put("amount", amount);
		param.put("type", type);
		param.put("area", area);
		param.put("notify_url", notify_url);
		param.put("sign", sign);
		Response res=Http.create(HttpUtil.getServerPath(request)+"api/receiveOrder").body(param).post().send().getResponse();
		if(res.getStatus()==0)
		{
			result.setCode(0);
			result.setMsg("网络异常");
			result.setData("");
			return result;
		}
		JSONObject json=JSONObject.fromObject(res.getResult());
		result.setCode(json.getInt("code"));
		result.setMsg(json.getString("msg"));
		result.setData("");
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/cancel.html")
	public Result cancel(HttpServletRequest request,HttpServletResponse response,Long id) throws IOException {
		Result result=new Result();
		try {
			ChargeAccountBean chargeAccount=chargeAccountService.getById(id);
			if(chargeAccount==null)
			{
				result.setCode(1);
				result.setMsg("订单不存在");
				return result;
			}
			if(chargeAccount.getCharge_status()==2||chargeAccount.getStatus()==-3)
			{
				result.setCode(1);
				result.setMsg("该订单状态不可取消");
				return result;
			}
			OrderBean lastOrder=orderService.getLastByChargeAccountId(chargeAccount.getId());
			if(lastOrder!=null&&lastOrder.getCreate_time()>System.currentTimeMillis()/1000-GlobalConfig.query_time_out)
			{
				result.setCode(1);
				result.setMsg("该订单正在充值中，不可取消");
				return result;
			}
			ChargeAccountBean updateModel=new ChargeAccountBean();
			updateModel.setId(chargeAccount.getId());
			updateModel.setStatus(-3);
			updateModel.setRemarks("手动取消");
			updateModel.setUpdate_time(System.currentTimeMillis()/1000);
			chargeAccountService.update(updateModel);
			result.setCode(0);
			result.setMsg("操作成功");
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(500);
			result.setMsg(e.getMessage());
			return result;
		}
	}
	
	@RequestMapping(value = "/testChargePage.html")
	public ModelAndView testChargePage(HttpServletRequest request,HttpServletResponse response,ModelAndView mav) throws IOException {
		mav.setViewName("admin/charge/testCharge");
		return mav;
	}

}
